package cn.wolfcode.mq;

import cn.wolfcode.ws.WebSocketServer;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author hkj
 * @email 1349091387@qq.com
 * @date 2022/1/2
 * 源码允许修改，并且本人十分乐意有 大佬 来对代码进行 随 意 调 教
 **/
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "MQOrderResultListener",topic = MQConstant.ORDER_RESULT_TOPIC)
public class MQOrderResultListener implements RocketMQListener<OrderMQResult> {

    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        log.info("进入消息队列中");
        try {
           Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //把orderMQResult对象直接推送给客户端
        String token = orderMQResult.getToken();
        WebSocketServer webSocketServer = WebSocketServer.clients.get(token);
        if(webSocketServer != null){
            try {
                //如果不为null,就推送消息
                webSocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
